<template>
  <a-radio-group :value="fakeValue" :options="config.options" v-bind="$attrs" @change="onChange" />
</template>
<script>
export default {
  name: 'SRadio',
  props: {
    code: String,
    url: String,
    data: {
      type: Array,
      required: false
    },
    modelValue: {
      type: String,
      required: false
    }
  },
  emits: ['change', 'update:modelValue'],
  data() {
    return { config: { options: this.data || [] }, fakeValue: undefined }
  },
  watch: {
    modelValue(val) {
      this.fakeValue = val
    },
    data() {
      this.config.options = this.data
    },
    url() {
      this.loadData()
    },
    code() {
      this.loadData()
    }
  },
  created() {
    this.fakeValue = this.modelValue
    this.loadData()
  },
  methods: {
    getLabel() {
      const labels = []
      if (this.fakeValue) {
        if (Array.isArray(this.fakeValue)) {
          this.fakeValue.forEach((item) => {
            const r = this.config.options.find((v) => v.value == item)
            if (r) {
              labels.push(r.label)
            }
          })
        } else {
          const r = this.config.options.find((v) => v.value == this.fakeValue)
          if (r) {
            labels.push(r.label)
          }
        }
      }
      return labels.toString()
    },
    loadData() {
      if (this.url) {
        this.$api.GET(this.url).then((res) => {
          const groups = []
          if (res.data) {
            res.data.forEach((item) => {
              groups.push({ label: item.text, value: item.value })
            })
          }
          this.config.options = groups
        })
      } else if (this.code) {
        this.$api
          .GET('/data/dict/item/selectListByGroupId', { groupIds: this.code })
          .then((res) => {
            const groups = []
            if (res.data) {
              res.data[this.code].forEach((item) => {
                groups.push({ label: item.text, value: item.value })
              })
            }
            this.config.options = groups
          })
      }
    },
    refreshData() {
      this.loadData()
    },
    onChange(val) {
      this.$emit('update:modelValue', val.target.value)
      this.$emit('change', val.target.value)
    }
  }
}
</script>
